#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QStackedLayout>
#include <QMenu>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    m_webView = new QWebEngineView(this);
    QStackedLayout * stackLayout = new QStackedLayout(ui->frame);
    ui->frame->setLayout(stackLayout);
    stackLayout->addWidget(m_webView);

    m_webView->setPage(new QSslPage(m_webView));
    m_webView->setContextMenuPolicy(Qt::CustomContextMenu);
    m_webView->load(QUrl::fromUserInput(QString::fromUtf8("http://127.0.0.1/testwebchannel.html")));
    ui->editURL->setText(QString::fromUtf8("http://127.0.0.1/testwebchannel.html"));

    m_inspector = nullptr;
    QObject::connect(m_webView, &QWidget::customContextMenuRequested, this, [this](){
        QMenu * menu = new QMenu(this);
        QAction * action = menu->addAction(QString::fromUtf8("Inspect"));
        QObject::connect(action, &QAction::triggered, this, [this](){
            if (this->m_inspector)
            {
                delete this->m_inspector;
                this->m_inspector = nullptr;
            }
            this->m_inspector = new Inspector(this);
            this->m_inspector->show();
        });
        menu->exec(QCursor::pos());
    });

    QObject::connect(ui->btnGo, &QPushButton::clicked, this, [this](){
        QString url = ui->editURL->text();
        if (! url.isEmpty()) {
            m_webView->load(QUrl::fromUserInput(url));
        }
    });

    QObject::connect(ui->btnRefresh, &QPushButton::clicked, this, [this](){
        m_webView->reload();
    });

    m_jsContext = new JsContext(this);
    m_webChannel = new QWebChannel(this);
    QHash<QString, QObject *> hash;
    hash.insert(QString::fromUtf8("context"), m_jsContext);
    m_webChannel->registerObjects(hash);
    m_webView->page()->setWebChannel(m_webChannel);
    QObject::connect(m_jsContext, &JsContext::recvMsg, this, [this](const QString & msg){
        ui->statusBar->showMessage(QString::fromUtf8("接收到来自页面的消息：%1").arg(msg), 3000);
    });

    QObject::connect(ui->btnSendMsg, &QPushButton::clicked, this, [this](){
        QString msg = ui->editMsg->text();
        if (! msg.isEmpty()) {
            m_jsContext->sendMsg(m_webView->page(), msg);
        }
    });
}

MainWindow::~MainWindow()
{
    if (ui)
    {
        delete ui;
        ui = nullptr;
    }
}

MainWindow *MainWindow::operator &()
{
    return this;
}

const MainWindow *MainWindow::operator &() const
{
    return this;
}
